﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Security.AccessControl;
using Traceability.Commont.Domains.AnimalsDomainFiles;
using Traceability.Commont.DTOs;
using Traceability.Commont.DTOs.CommontFiles;
using Traceability.Commont.Infrastructures.Interfaces;

namespace U.Enterprise.Api.Applications.AdmissionRegistrationFile
{
    /// <summary>
    /// 磅秤设置列表
    /// </summary>
    public class ScaleSetUpSelectHander : IRequestHandler<ScaleSetUpSelectListCommand, PageDTO<ScaleSelectListDTO>>
    {
        private readonly IBateRepository<Scale> scale;
        private readonly IBateRepository<ScaleType> type;

        public ScaleSetUpSelectHander(IBateRepository<Scale> scale, IBateRepository<ScaleType> type)
        {
            this.scale = scale;
            this.type = type;
        }

        public async Task<PageDTO<ScaleSelectListDTO>> Handle(ScaleSetUpSelectListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                PageDTO<ScaleSelectListDTO> res = new PageDTO<ScaleSelectListDTO>() { pageCount = 0, totalCount = 0 };
                var list = from a in scale.GetAll()
                          join b in type.GetAll() on a.ScaleTypeId equals b.ScaleTypeid
                          select new ScaleSelectListDTO()
                          {
                              Scaleid=a.Scaleid,
                              ScaleName =a.ScaleName,
                              ScaleTypename=b.ScaleTypename,
                              TareWeightDeduction=a.TareWeightDeduction,
                              NumberOfPieces=a.InAndOutOfStorage=="0"?"启用":"禁用",
                              Warehouse="-",
                              InAndOutOfStorage= a.InAndOutOfStorage == "0" ? "启用" : "禁用",
                              Operator=a.Operator,
                              UseType=a.UseType,
                              CreatedBy = a.CreatedBy,
                              CreateTime = a.CreateTime,
                              ModifiedBy= a.ModifiedBy,
                              UpdateTime= a.CreateTime
                          };
                if (!string.IsNullOrEmpty(request.Name))
                {
                    list = list.Where(x => x.ScaleName.Contains(request.Name));
                }
                res.totalCount=list.Count();
                res.pageCount=(int)Math.Ceiling(list.Count()*1.0/request.pageSize);
                list=list.OrderBy(x=>x.Scaleid).Skip((request.pageIndex-1)*request.pageSize).Take(request.pageSize);
                res.Lists = list.ToList();
                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
